<?php

namespace app\admin\controller\dormitory;

use app\admin\model\Admin;
use app\admin\model\DormitoryBuilding;
use app\admin\model\DormitoryDorm;
use app\admin\model\DormitoryGarden;
use app\common\controller\Backend;
use think\Db;
use think\Hook;
use think\Log;

class Building extends Backend
{
    /**
     * @var \app\admin\model\DormitoryBuilding
     */
    protected $model = null;
    protected $searchFields = 'id,name';
    protected $noNeedRight = ['searchList', 'cxSelect', 'buildingFloorList'];

    protected $gardenData = [];
    protected $dormCategoryData = [];
    protected $dormTypeData = [];
    protected $adminData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('DormitoryBuilding');


        $result = collection(DormitoryGarden::all())->toArray();

        foreach ($result as $k => $v) {
            $this->gardenData[$v['number']] = $v['name'];
        }

        $this->dormCategoryData = DormitoryDorm::$categoryList;

        $this->dormTypeData = DormitoryDorm::$typeList;

        $childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $adminList = Admin::whereIn('id', $childrenAdminIds)->field('id,nickname')->select();
        foreach ($adminList as $key => $value) {
            $this->adminData[$value->id] = $value->nickname;
        }

        $this->view->assign('gardenData', $this->gardenData);
        $this->view->assign('dormCategoryData', $this->dormCategoryData);
        $this->view->assign('dormTypeData', $this->dormTypeData);
        $this->view->assign('adminData', $this->adminData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__ADMIN__ d', 'd.id = a.creator_id', 'left')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__ADMIN__ d', 'd.id = a.creator_id', 'left')
                ->where($where)
                ->field('a.*,c.name as garden_name,d.nickname as creator_name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['dorm_type_text'])->toArray();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $init_dorm = $this->request->post("init_dorm");

            if ($params) {

                $params['creator_id'] = $this->auth->id;

                // 启动事务
                Db::startTrans();
                try{

                    $result = $this->model->validate('DormitoryBuilding.add')->save($params);

                    if ($result === false) {
                        $this->error($this->model->getError());
                    }

                    if ($init_dorm) {
                        Db::query("call init_building_dorm('{$params['garden_number']}','{$params['number']}','{$params['name']}',{$params['floor_count']},{$params['floor_dorm_count']},{$params['dorm_type']},{$params['dorm_category']},{$params['dorm_bed_count']},{$params['dorm_price']},{$params['creator_id']})");
                    }

                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    $this->error($this->model->getError() ? $this->model->getError() : __('Init Dorm Fail'));
                }

                //Hook::listen('qrcode_init');

                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');

            $init_dorm = $this->request->post("init_dorm");
            if ($params) {

                $validate = Validate('DormitoryBuilding');
                $res = $validate->scene('edit')->check($params);
                if (!$res) {
                    $this->error($validate->getError());
                }

                $params['creator_id'] = $this->auth->id;

                // 启动事务
                Db::startTrans();
                try{

                    $row->except(['garden_number', 'number'])->save($params);

                    if ($init_dorm) {

                        DormitoryDorm::where('building_number', $row['number'])->where('garden_number', $row['garden_number'])->delete();
                        $sql = "call init_building_dorm('{$row['garden_number']}','{$row['number']}','{$params['name']}',{$params['floor_count']},{$params['floor_dorm_count']},{$params['dorm_type']},{$params['dorm_category']},{$params['dorm_bed_count']},{$params['dorm_price']},{$params['creator_id']})";
                        Db::query($sql);
                    }

                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    $this->error($this->model->getError() ? $this->model->getError() : __('Init Dorm Fail'));
                }

                //Hook::listen('qrcode_init');

                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $ids = explode(',', $ids);
            $ids = array_unique($ids);

            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 联动搜索
     * 根据园区号获取楼栋列表
     */
    public function cxSelect()
    {
        $garden_number = $this->request->request('garden_number');
        $dorm_type = $this->request->request('dorm_type', 0);

        $cond['garden_number'] = $garden_number;
        if ($dorm_type) {
            $cond['dorm_type'] = ['in', [$dorm_type, 3]];
        }

        $result = $this->model->where($cond)->select();

        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['value' => $value['number'], 'name' => $value['name'], 'id' => $value['id']];
        }

        $this->success('', null, $searchList);
    }

    /**
     * 根据楼栋id获取楼层数
     */
    public function buildingFloorCount()
    {
        $building_id = $this->request->request('building_id');

        $result = $this->model->find($building_id);

        $floor_count = 0;
        if ($result)
            $floor_count = $result->floor_count;

        $this->success('', null, ['floor_count' => $floor_count ]);
    }

    public function statistics()
    {
        if ($this->request->isAjax()) {
            $list = $this->model->alias('a')
                ->join('__DORMITORY_GARDEN__ b', 'b.number = a.garden_number', 'left')
                ->join('__DORMITORY_DORM__ c', 'c.building_number = a.number and c.garden_number = a.garden_number', 'left')
                ->join('__DORMITORY_DORM_BED__ d', 'd.dorm_number = c.number and d.building_number = a.number and d.garden_number = a.garden_number', 'left')
                ->where('c.status', DormitoryDorm::NORMAL)
                ->field('COUNT(d.id) total_count,
                        SUM(CASE WHEN d.status = 2 THEN 1 ELSE 0 END) used_count, 
                        SUM(CASE WHEN d.status = 2 AND c.type = 1 THEN 1 ELSE 0 END) used_boy_count, 
                        SUM(CASE WHEN d.status = 2 AND c.type = 2 THEN 1 ELSE 0 END) used_girl_count,
                        SUM(CASE WHEN d.status = 1 THEN 1 ELSE 0 END) free_count, 
                        SUM(CASE WHEN d.status = 1 AND c.type = 1 THEN 1 ELSE 0 END) free_boy_count, 
                        SUM(CASE WHEN d.status = 1 AND c.type = 2 THEN 1 ELSE 0 END) free_girl_count')
                ->select();

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }



}
